<?php


namespace app\api\controller\xilujob;

/**
 * 公司
 */

use addons\xilujob\controller\WeixinMini;
use addons\xilujob\library\Upload;
use app\common\controller\xilujob\XilujobApi;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\CompanyViewLog;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\ResumeDownload;
use app\common\model\xilujob\UserBlacklistCompany;
use app\common\model\xilujob\UserCollection;
use app\common\model\xilujob\XilujobUser;
use think\Db;
use think\db\Query;
use think\Exception;

class Company extends XilujobApi
{
    protected $noNeedLogin = ['lists','detail','jobs'];
    protected $noNeedRight = ['*'];
    protected $restrictedActions = ['*'];


    /**
     * @apiTitle (公司基本信息)
     */
    public function company() {
        $user = $this->auth->getUser();
        $enterpriseInfo = EnterpriseInfo::get(['user_id'=>$user->id]);
        $userinfo = XilujobUser::formatApiRet($user);
        $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
        $recommend_resumes = \app\common\model\xilujob\Resume::recommendResumes($xilujobuser->group_model, ['pagesize'=>999,'city_id'=>$this->cityId]);
        $data = [
            'userinfo' => $userinfo,
            'summary' => [
                'avatar' => $user->avatar,
                'nickname' => $user->nickname,
                'company_name' => $enterpriseInfo->company_name,
                'company_address' => $enterpriseInfo->address,
                'message_count' => $xilujobuser->system_message + $xilujobuser->discover_message + $xilujobuser->activity_message,
                'recommend_resumes_count' => $recommend_resumes->toArray()['total'],
                'apply_count' => \app\common\model\xilujob\JobApply::where(['company_id'=>$xilujobuser->group_model->id,'status'=>\app\common\model\xilujob\JobApply::STATUS_APPLY_SENT])->count(),
                'interview_count' => \app\common\model\xilujob\JobInterview::where(['company_id'=>$xilujobuser->group_model->id,'status'=>['in',[\app\common\model\xilujob\JobInterview::STATUS_INTERVIEW_SENT, \app\common\model\xilujob\JobInterview::STATUS_INTERVIEW_ACCEPTED]]])->count(),
                'resume_download_count' => ResumeDownload::where('company_id', $xilujobuser->group_model->id)->count(),
                'info_complete' => $enterpriseInfo->info_complete,
                'job_count' => \app\common\model\xilujob\Job::where('publisher_id', $xilujobuser->group_model->id)->count(),
                'discover_post_life_count' => $xilujobuser->discover_message,

                'resume_action_num'     => $enterpriseInfo->resume_action_num,
                'job_num_limit'         => $enterpriseInfo->job_num_limit,
                'interview_num'         => $enterpriseInfo->interview_num,
                'job_refresh_num'       => $enterpriseInfo->job_refresh_num,
                'address_num'           => \app\common\model\xilujob\CompanyAddress::where("company_id",$enterpriseInfo->company_id)->count(1),
            ]
        ];
        $this->success('', $data);
    }

    /**
     * @ApiTitle (公司列表)
     * @ApiSummary  (公司公共方法，包含推荐、搜索等)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/lists)
     * @ApiHeaders (name=cityid, type=int, required=true, description="城市id")
     * @ApiParams (name="district_id", type="integer", required='', description="地区id")
     * @ApiParams (name="distance", type="integer", required='', description="半径内")
     * @ApiParams (name="pos", type="string", required='',sample="lng,lat", description="经度,纬度")
     * @ApiParams (name="category_id", type="int", required='', description="行业id")
     * @ApiParams (name="scale_id", type="int", required='', description="规模id")
     * @ApiParams (name="q", type="string", required='', description="搜索地址关键词")
     * @ApiParams (name="sort", type="int", required='', description="排序")
     * @ApiParams (name="pagesize", type="int", required='', description="每页数量")
     * @ApiParams (name="page", type="int", required='', description="页码")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="array", sample="[city_name, industry_category_name,  company_scale_name,'benefits':[{'id':'int','name':'string'}],'enterpriseinfo':[{'id':'int','company_name':'string','full_name':'string','city_id':'int','company_scale_id':'int','industry_category_id':'int','logo':'string'}],'statistics':[{'id':'int','job_count':'int','interview_comment_count':'int'}]]", description="扩展数据返回")
     */
    public function lists(){
        $params = $this->request->param();
        $params['city_id'] = $this->cityId;
        $lists = CompanyProfile::searchCompanies($params);
        $this->success('查询成功',$lists);
    }


    /**
     * @ApiTitle (企业的详细信息)
     *
     */
    public function detail($company_id) {
        $company = CompanyProfile::get($company_id);
        if(!$company || $company->user->status!='normal') {
            $this->error('没有找到相关企业信息');
        }
        $enterpriseInfo = EnterpriseInfo::field('id,full_name,company_name,environment_images,industry_category_id,intro,company_type_id,lat,lng,address,company_scale_id,logo')
            ->with([
                'company_scale'=>function($query){$query->withField('id,name');},
                'company_properties'=>function($query){$query->withField('id,name');},
                'industry_category'=>function($query){$query->withField('id,name');},
                'city'=>function($query){$query->withField('id,shortname');},
                'benefits'
            ])
            ->where('company_id',$company->id)
            ->find();
        $company->enterpriseinfo = $enterpriseInfo;
        if($this->auth->id) {
            $canComment = Db::name('xilujob_job_interview')->where([
                    'user_id'=>$this->auth->id, 'company_id'=>$company_id,
                    'status'=> \app\common\model\xilujob\JobInterview::STATUS_INTERVIEW_PASSED
                ])->count()>0 && Db::name('xilujob_company_comment')->where(['user_id'=>$this->auth->id,'company_id'=>$company_id])->count()==0;
        }else {
            $canComment = false;
        }

        $commentCount = \app\common\model\xilujob\CompanyComment::where('company_id', $company_id)->where('status',1)->count();

        $isFav = UserCollection::isFav($this->auth->id, $company_id, UserCollection::TYPE_COMPANY);
        try {
            CompanyViewLog::viewCompany($this->auth->id, $company_id);
        }catch (Exception $e){
            //$this->error($e->getMessage());
        }


        $this->success('',['company'=>$company,'is_fav'=>$isFav,'can_comment'=>$canComment,'comment_count'=>$commentCount]);
    }

    /**
     * @ApiTitle (企业发布的职位)
     * @ApiSummary  (企业发布的职位)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/jobs)
     * @ApiHeaders (name=token,type=string, description="Token")
     * @ApiParams (name=company_id,type=int, description="公司id")
     */
    public function jobs() {
        $company_id = $this->request->param('company_id',0);
        $jobs = \app\common\model\xilujob\Job::where('publisher_id', $company_id)
            ->where('status', \app\common\model\xilujob\Job::STATUS_ENABLED)
            ->field('id,publisher_id,type,job_name,job_category_id,city_id,district_id,town_id,in_hurry,direct,shop,red_packet,'.
                'work_experience_id,education_level_id,salary_type,salary_min,salary_max,refresh_date,red_packet_instruction')
            ->with([
                'city'=>function(Query $query){$query->withField('id,name');},
                'district'=>function(Query $query){$query->withField('id,name');},
                'work_experience'=>function(Query $query){$query->withField('id,name');},
                'education_level'=>function(Query $query){$query->withField('id,name');},
                'benefits'=>function(Query $query){$query->withField('id,name');},
                'enterpriseinfo'=>function(Query $query){$query->withField('id,logo,company_name,full_name');}
            ])
            ->select();
        $this->success('查询成功',['jobs'=>$jobs]);
    }

    /**
     * @ApiTitle (收藏&取消收藏)
     * @ApiSummary  (收藏&取消收藏)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/toggle_fav)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function toggle_fav() {
        $companyId = $this->request->post('company_id');
        $result = UserCollection::toggleFav($this->auth->id, $companyId, UserCollection::TYPE_COMPANY);
        $this->success('操作成功',['is_fav'=>$result]);
    }

    /**
     * @ApiTitle (收藏列表)
     * @ApiSummary  (收藏列表)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/fav_list)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function fav_list() {
        $companies = CompanyProfile::with([
            'benefits'=>function(Query $query){$query->withField('id,name');},
            'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name,logo,city_id,company_scale_id,industry_category_id');},
            'statistics' => function(Query $query){$query->withField('id,job_count');},
        ])->join('xilujob_user_collection c', 'company_profile.id=c.collection_id')
            ->where('c.collection_type', UserCollection::TYPE_COMPANY)
            ->where('c.user_id', $this->auth->id)
            ->join('XilujobArea area','enterpriseinfo.city_id=area.id','LEFT')
            ->join('XilujobIndustryCategory category', 'enterpriseinfo.industry_category_id=category.id', 'LEFT')
            ->join('XilujobCompanyScale scale', 'enterpriseinfo.company_scale_id=scale.id', 'LEFT')
            ->field('area.shortname as city_name, category.name as industry_category_name, scale.name as company_scale_name')
            ->paginate();
        $this->success('查询成功',$companies);
    }

    /**
     * @ApiTitle (我看过的记录)
     * @ApiSummary  (我看过的记录)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/my_look)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function my_look() {
        $paginator = CompanyProfile::with([
            'benefits'=>function(Query $query){$query->withField('id,name');},
            'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name,logo');},
            'statistics' => function(Query $query){$query->withField('id,job_count');},
        ])->join('xilujob_company_view_log log','company_profile.id=log.company_id')
            ->where('log.user_id', $this->auth->id)
            ->order('log.view_time','desc')
            ->join('XilujobArea area','enterpriseinfo.city_id=area.id','LEFT')
            ->join('XilujobIndustryCategory category', 'enterpriseinfo.industry_category_id=category.id', 'LEFT')
            ->join('XilujobCompanyScale scale', 'enterpriseinfo.company_scale_id=scale.id', 'LEFT')
            ->field('company_profile.*,log.view_time,area.shortname as city_name, category.name as industry_category_name, scale.name as company_scale_name')
            ->paginate();
        $this->success('查询成功',$paginator);
    }

    /**
     * @ApiTitle (看过我（个人）的企业列表)
     * @ApiSummary  (我看过的记录)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/look_my)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function look_my() {
        $resume = \app\common\model\xilujob\Resume::getUserResume($this->auth->id);
        if(!$resume) {
            $this->success('',['companies'=>[]]);
        }
        $paginator = CompanyProfile::with([
            'benefits'=>function(Query $query){$query->withField('id,name');},
            'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name,logo');},
            'statistics' => function(Query $query){$query->withField('id,job_count');},
        ])->join('xilujob_resume_view_log log','company_profile.id=log.company_id')
            ->where('log.resume_id', $resume->id)
            ->order('log.view_time','desc')
            ->join('XilujobArea area','enterpriseinfo.city_id=area.id','LEFT')
            ->join('XilujobIndustryCategory category', 'enterpriseinfo.industry_category_id=category.id', 'LEFT')
            ->join('XilujobCompanyScale scale', 'enterpriseinfo.company_scale_id=scale.id', 'LEFT')
            ->field('company_profile.*,log.view_time,area.shortname as city_name, category.name as industry_category_name, scale.name as company_scale_name')
            ->paginate();
        $this->success('查询成功',$paginator);
    }

    /**
     * @ApiTitle (公司海报)
     * @ApiSummary  (公司海报)
     * @ApiMethod (GET)
     * @ApiRoute (api/xilujob.company/company_blacklist)
     */
    public function poster_info() {
        $id = $this->request->param('id');
        $company = CompanyProfile::get($id);
        //if(!$company->miniapp_code) {
            $uid = $this->auth->id;
            $xiluuser = XilujobUser::get(['user_id'=>$uid]);
            $wx = new WeixinMini();
            $page = "pages/user/company_info";
            $res = $wx->getUnlimited("id=".$id."&uid=".$uid."&group=".$xiluuser->group_id,$page);
            if(!$res) $this->error('获取小程序二维码失败');
            $path = "/runtime/xilujob/company/";
            if (!file_exists(ROOT_PATH . $path)) {
                @mkdir(ROOT_PATH . $path, 0777, true);
            }
            $filename = $company->id.'.png';
            $qrcode = $path.$filename;
            file_put_contents(ROOT_PATH.$qrcode,$res);

            // 上传成功后该文件将被删除，请务必使用临时文件，这里$tempFile为你服务器准备上传的文件
            $tempFile = ROOT_PATH . $qrcode;
            $qrcode = (new Upload())->uploadApi($tempFile);
            $company->save(['miniapp_code'=>cdnurl($qrcode,true)]);
        //}
        $enterprise = EnterpriseInfo::where('company_id',$company->id)->find();
        $jobs = \app\common\model\xilujob\Job::where('status','1')->where('publisher_id', $id)->field('id,job_name,num')
            ->limit(0,3)->select();
        $totalJob = \app\common\model\xilujob\Job::where('status','1')->where('publisher_id', $id)->count();
        $text3 = '';
        foreach($jobs as $job) {
            $text3 .= "{$job->job_name}{$job->num}名/";
        }
        $text3 = preg_replace('/\/$/','',$text3);
        $this->success('',[
            'text1' => $enterprise->company_name,
            'text2'=>'企业直招', 'tip'=>'长按识别二维码，查看企业详情',
            'text3' => $text3, 'text4' =>"正在招聘{$totalJob}个职位",
            'img2'=>cdnurl($company->miniapp_code,true),
            'img1'=>cdnurl($enterprise->logo,true)
        ]);
    }

    /**
     * @ApiTitle (个人获取黑名单列表)
     * @ApiSummary  (个人获取黑名单列表)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/company_blacklist)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function company_blacklist() {
        $blacklist = UserBlacklistCompany::getBlacklist($this->auth->id);
        $this->success('查询成功', $blacklist);
    }

    /**
     * @ApiTitle (个人添加删除黑名单)
     * @ApiSummary  (个人添加删除黑名单)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/set_blacklist_company)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function set_blacklist_company() {
        $companyIds = $this->request->post('company_ids/a');
        Db::startTrans();
        foreach($companyIds as $companyId) {
            $blacklist = UserBlacklistCompany::where([
                'user_id'=>$this->auth->id,
                'company_id'=>$companyId
            ])->find();
            if($blacklist) {
                $blacklist->delete();
            }else {
                $count = UserBlacklistCompany::where('user_id', $this->auth->id)->count();
                if($count>=5) {
                    Db::rollback();
                    $this->error('最多添加5个,您已添加'.$count.'个');
                }
                UserBlacklistCompany::create([
                    'user_id'=>$this->auth->id,
                    'company_id'=>$companyId
                ]);
            }
        }
        Db::commit();
        $this->success();

    }

    /**
     * @ApiTitle (添加黑名单时搜索公司名)
     * @ApiSummary  (个人添加删除黑名单)
     * @ApiMethod (POST)
     * @ApiRoute (api/xilujob.company/search_company)
     * @ApiHeaders (name=token,type=string, description="Token")
     */
    public function search_company() {
        $q = $this->request->param('q');
        if(!$q) {
            $this->success('',[]);
        }

        $userId = $this->auth->id;
        $list = EnterpriseInfo::alias('i')
            ->join('xilujob_user u','i.user_id=u.user_id')
            ->whereIn('enterprise_group_id',[\app\common\model\xilujob\XilujobUser::GROUP_COMPANY])
            ->where('company_name','like', "%$q%")
            ->where('i.id','not in', function(Query $query) use ($userId) {
                $query->name('xilujob_user_blacklist_company')->where('user_id',$userId)->field('company_id');
            })
            ->field('i.company_id as id,company_name')
            ->select();
        $this->success('',$list);
    }

}